// pages/recommendSong/recommendSong.js
import request from '../../../utils/request'
import PubSub from 'pubsub-js'
const appInstance = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    day: '', //天
    month: '', //月
    recommendList: [], //推荐列表数据
    index: 0, // 点击音乐的下标
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 判断用户是否登录
    let userInfo = wx.getStorageSync('userInfo')
    if (!userInfo)
      return wx.showToast({
        title: '请先登录',
        icon: 'error',
        duration: 1500,
        mask: false,
        success: result => {
          wx.reLaunch({
            url: '/pages/login/login',
          })
        },
      })

    // 获取今天的日期
    this.setData({
      day: new Date().getDate(),
      month: new Date().getMonth() + 1,
    })
    // 获取每日用户推荐数据
    this.getRecommendList()

    PubSub.subscribe('switchType', (_, type) => {
      let { recommendList, index } = this.data
      if (type === 'pre') {
        index === 0 && (index = recommendList.length)
        index = index - 1
      } else if (type === 'next') {
        index === recommendList.length - 1 && (index = -1)
        index = index + 1
      } else {
        index =
          index === this.data.index
            ? Math.floor(Math.random() * recommendList.length)
            : Math.floor(Math.random() * recommendList.length)
      }
      // 更新下标
      this.setData({
        index,
      })
      let musicId = recommendList[index].id
      //  将music回传给songDetail页面
      PubSub.publish('musicId', musicId)
    })
  },
  // 获取每日用户推荐数据的回调
  async getRecommendList() {
    let { recommend } = await request('/recommend/songs')
    this.setData({
      recommendList: recommend,
    })
    appInstance.globalData.musicList = recommend.map(item => item.id)
  },
  // 跳转至音乐详情页
  toSongDetail(e) {
    let { song, index } = e.currentTarget.dataset
    this.setData({
      index,
    })
    wx.navigateTo({
      url: '/songPackage/pages/songDetail/songDetail?ids=' + song.id,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
})
